import { Inject, Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { spiderBaiduAi } from 'src/utils/init-data';
import { PrismaService } from 'src/libs/prisma/prisma.service';
import { RedisService } from 'src/libs/redis/redis.service';
import { getCurrentDateNumber } from 'src/utils';

@Injectable()
export class TaskService {
  @Inject(PrismaService)
  private readonly prisma: PrismaService;

  @Inject(RedisService)
  private readonly redisService: RedisService;

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async resetDailyPoints() {
    const roles = await this.prisma.userRole.findMany();
    const normalRoleId = roles.find((role) => role.role === 'NORMAL')?.id;
    const vipRoleIds = roles.filter((role) => role.role !== 'NORMAL')?.map((role) => role.id);
    // 1 先降级过期用户
    await this.prisma.user.updateMany({
      where: {
        AND: [{ vipEndTime: { lt: new Date() } }, { roleId: { in: vipRoleIds } }],
      },
      data: {
        roleId: normalRoleId,
      },
    });
    // 2 根据每个角色的积分，初始化每个用户积分
    const updates = roles.map((role) =>
      this.prisma.user.updateMany({
        where: { roleId: role.id },
        data: { points: role.refreshPoint },
      }),
    );
    await Promise.all(updates);
  }
}
